package com.xbk.seckill.stock.application.event.handler;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.event.EventHandler;
import com.alibaba.cola.event.EventHandlerI;
import com.alibaba.fastjson.JSON;
import com.xbk.seckill.stock.application.cache.SeckillStockBucketCacheService;
import com.xbk.seckill.stock.domain.event.SeckillStockBucketEvent;
import com.xbk.seckill.stock.domain.model.enums.SeckillStockBucketEventType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

/**
 * 基于Cola的库存事件处理器
 *
 * @author xiexu
 * @date 2025/3/10 22:36
 */
@Slf4j
@EventHandler
@ConditionalOnProperty(name = "message.mq.type", havingValue = "cola")
public class SeckillStockColaEventHandler implements EventHandlerI<Response, SeckillStockBucketEvent> {

    @Autowired
    private SeckillStockBucketCacheService seckillStockBucketCacheService;

    @Override
    public Response execute(SeckillStockBucketEvent seckillStockBucketEvent) {
        log.info("cola|stockEvent|接收库存事件|{}", JSON.toJSON(seckillStockBucketEvent));
        if (seckillStockBucketEvent == null || seckillStockBucketEvent.getId() == null) {
            log.info("cola|stockEvent|订单参数错误");
            return Response.buildSuccess();
        }
        // 开启了库存分桶，就更新缓存数据
        if (SeckillStockBucketEventType.ENABLED.getCode().equals(seckillStockBucketEvent.getStatus())) {
            seckillStockBucketCacheService.tryUpdateSeckillStockBucketCacheByLock(seckillStockBucketEvent.getId(), false);
        }
        return Response.buildSuccess();
    }

}
